﻿using System;
using System.Collections.Generic;
using System.Text;
using FlickrNet;

namespace Bbq.Gallery
{
    internal class FlickrImporter : ImporterBase
    {
        private const int MAX_RETURNED_ITEMS_PER_PAGE = 500;
        private string tagNames = null;
        private string userName = null;
        /// <summary>
        /// Initializes a new instance of the <see cref="FlickrImporter"/> class.
        /// </summary>
        /// <param name="userName">Name of the user (use email).</param>
        /// <param name="tagNames">The tags (comma delimited) to search for.</param>
        public FlickrImporter(string userName, string tagNames)
        {
            this.tagNames = tagNames;
            this.userName = userName;
            if (string.IsNullOrEmpty(this.userName))
                this.userName = System.Web.Configuration.WebConfigurationManager.AppSettings["FlickrDefaultUserName"];
        }

        /// <summary>
        /// Imports the specified album.
        /// </summary>
        /// <param name="album">The album.</param>
        public override void Import(GalleryAlbum album, bool clearAllItems)
        {
            Flickr flickr = new Flickr();
            FoundUser user = flickr.PeopleFindByEmail(userName);
            if (user == null)
                return;
            PhotoSearchOptions options = new PhotoSearchOptions(user.UserId, tagNames, TagMode.AnyTag);
            //Optimize returned data
            options.Extras = PhotoSearchExtras.DateTaken | PhotoSearchExtras.OriginalFormat | 
                PhotoSearchExtras.OwnerName;
            options.SortOrder = PhotoSearchSortOrder.DateTakenDesc;
            //Reduct the number of HTTP request
            options.PerPage = FlickrImporter.MAX_RETURNED_ITEMS_PER_PAGE;
            Photos photos = null;

            bool isStarted = false;

            //Perform importing
            do
            {
                photos = flickr.PhotosSearch(options);
                if (photos == null || photos.PhotoCollection.Length == 0)
                    break;
                //Begin import
                if (!isStarted)
                {
                    isStarted = true;
                    Gallery.GalleryProvider.BeginImport(album);
                    //Whether we clear all current items
                    if (clearAllItems)
                    {
                        Gallery.GalleryProvider.ClearItems4Importing();
                    }
                }

                //Perform importing
                foreach (Photo photo in photos.PhotoCollection)
                {
                    //Try to get the original Url
                    Sizes info = flickr.PhotosGetSizes(photo.PhotoId);
                    string originalUrl = info.SizeCollection[info.SizeCollection.Length - 1].Source;
                    GalleryItem item = new GalleryItem(photo.Title);
                    item.ThumbnailUrl = photo.SmallUrl; //best fit for thumnbail of gallery
                    item.Url = originalUrl;
                    item.CreatedDate = photo.DateTaken;
                    item.AuthorName = photo.OwnerName;
                    item.IsExternal = true;
                    //Insert gallery item
                    Gallery.GalleryProvider.InsertImportEntry(item);
                }

                options.Page++;
                if (options.Page > photos.TotalPages)
                    break;
            } while (true);

            //Commit importing
            if (isStarted)
                Gallery.GalleryProvider.CommitImport();
        }
    }
}
